package net.cassite.pure.ioc.handlers.param;

import java.lang.annotation.Annotation;

import net.cassite.pure.ioc.AnnotationHandlingException;
import net.cassite.pure.ioc.IOCController;
import net.cassite.pure.ioc.Scope;
import net.cassite.pure.ioc.handlers.IrrelevantAnnotationHandlingException;
import net.cassite.pure.ioc.handlers.ParamAnnotationHandler;
import net.cassite.pure.ioc.handlers.ParamHandlerChain;
import net.cassite.style.reflect.MemberSup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Default implementation of ParamAnnotationHandler <br>
 * simply return the corresponding value of given parameter type.
 *
 * @author wkgcass
 */
public class DefaultParamHandler extends IOCController implements ParamAnnotationHandler {

        private static final Logger LOGGER = LoggerFactory.getLogger(DefaultParamHandler.class);

        @Override
        public boolean canHandle(Annotation[] annotations) {
                return true;
        }

        @Override
        public Object handle(Scope scope, MemberSup<?> caller, Class<?> cls, Class<?> expectedClass, Annotation[] toHandle, ParamHandlerChain chain) throws AnnotationHandlingException {
                LOGGER.debug("Entered DefaultParamHandler with args:\n\tcaller:\t{}\n\tcls:\t{}\n\ttoHandle:\t{}\n\tchain:\t{}",
                        caller, cls, toHandle, chain);
                if (scope.isBond(cls)) {
                        LOGGER.debug("Start handling with DefaultParamHandler");
                        LOGGER.debug("--cls {} is bond, retrieving from IOCController", cls);
                        return scope.getBondInstance(cls);
                } else {
                        try {
                                return chain.next().handle(scope, caller, cls, expectedClass, toHandle, chain);
                        } catch (IrrelevantAnnotationHandlingException e) {
                                LOGGER.debug("Start handling with DefaultParamHandler");
                                return get(scope, cls, expectedClass);
                        }
                }
        }

}
